<template>
	<el-dialog title="角色权限设置" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-tabs tab-position="top">
			<el-tab-pane label="菜单权限">
				<div class="treeMain">
					<el-tree ref="permission" node-key="id"  :data="menu.list" :props="menu.props" show-checkbox></el-tree>
				</div>
			</el-tab-pane>
		</el-tabs>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>

	export default {
		emits: ['success', 'closed'],
		data() {
			return {
				visible: false,
				isSaveing: false,
				menu: {
					list: [],
					checked: [],
					props: {
						label: (data)=>{
							return data.meta.title
						}
					}
				},
				roleId:0,
				data: {
					dataType :"1",
					list: [],
					checked: [],
					props: {},
					rule: ""
				},
				dashboard: "0",
			}
		},
		mounted() {
			this.getMenu()
		},
		methods: {
			open(roleId){
				this.roleId = roleId
				this.visible = true;
			},
			async submit(){
				this.isSaveing = true;
				//选中的和半选的合并后传值接口
				const checkedKeys = this.$refs.permission.getCheckedKeys().concat(this.$refs.permission.getHalfCheckedKeys())
				//console.log(checkedKeys)
				//console.log(this.roleId)
				const res = await this.$API.system.role.link.post({id:this.roleId,permissionIds:checkedKeys});
				this.isSaveing = false;
				if(res.code == 200){
					this.visible = false;
					this.$message.success("操作成功")
				}else{
					this.$alert(res.message, "提示", {type: 'error'})
				}
			},
			async getMenu(){
				const res = await this.$API.menu.list.post();
				this.menu.list = res.data
				//console.log(this.$refs.permission)
				//获取接口返回的之前选中的和半选的合并，处理过滤掉有叶子节点的key
				const permission = await this.$API.menu.role.post({id:this.roleId})
				if(permission.data.length>0){
					permission.data.forEach((item)=>{
						this.menu.checked.push(item.id)
					})
				}
				//this.menu.checked = [10000,10100]
				this.$nextTick(() => {
					let filterKeys = this.menu.checked.filter(key => this.$refs.permission.getNode(key).isLeaf)
					this.$refs.permission.setCheckedKeys(filterKeys, true)
				})
			},
		}
	}
</script>

<style scoped>
	.treeMain {height:280px;overflow: auto;border: 1px solid #dcdfe6;margin-bottom: 10px;}
</style>
